﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization.Formatters.Soap;
using System.IO;

namespace DicomScu.Scu
{
    [Serializable]
    public class ScuConfigDestinationCollection : ScuConfigCollection
    {
        int _localConfig = -1;
        public ScuConfig LocalConfig
        {
            get
            {
                if (_localConfig > -1 && this.ConfigCollection.Count > _localConfig)
                    return (ScuConfig)this.ConfigCollection[_localConfig];
                else
                    return null;
            }
            set
            {
                if (this.ConfigCollection.Contains(value))
                {
                    _localConfig = this.ConfigCollection.IndexOf(value);
                }
            }
        }

        public bool IsStartLocalOnStartup
        {
            get;
            set;
        }

        public string LocalStoreDirectoryConfig
        {
            get;
            set;
        }
        public override void MoveFirst(ScuConfig config)
        {
            ScuConfig local = LocalConfig;
            base.MoveFirst(config);
            if (local != null)
                _localConfig = ConfigCollection.IndexOf(local);
        }
        public override void MoveUp(ScuConfig config)
        {
            ScuConfig local = LocalConfig;
            base.MoveUp(config);
            if (local != null)
                _localConfig = ConfigCollection.IndexOf(local);
        }

        public static ScuConfigCollection GetFromFile(string ConfigPath)
        {
            ScuConfigDestinationCollection col;
            if (!File.Exists(ConfigPath))
            {
                col = new ScuConfigDestinationCollection();
            }
            else
            {
                SoapFormatter formatter = new SoapFormatter();
                using (FileStream fs = new FileStream(ConfigPath, FileMode.Open))
                {
                    try
                    {
                        col = (ScuConfigDestinationCollection)formatter.Deserialize(fs);
                    }
                    catch
                    {
                        col = new ScuConfigDestinationCollection();
                    }
                }
            }
            return col;
        }
    }
}
